<?php

namespace App\Http\Middleware;

use App\Common\Traits\ResponseTrait;
use App\Models\Strator\StratorAuthToken;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Auth\Guard;

class StratorAuthMiddleware
{
    use ResponseTrait;

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $bearerToken  = $request->bearerToken();
        if(empty($bearerToken)){
            return $this->unauthorized('请先登录');
        }
        $authToken=StratorAuthToken::where('token',$bearerToken)->first();
        if(empty($authToken)){
            return $this->unauthorized();
        }
        if(strtotime($authToken->expires_at)<time()){
            $authToken->delete();
            return $this->unauthorized();
        }

        $authToken->last_used_at=date('Y-m-d H:i:s');
        $authToken->expires_at=date('Y-m-d H:i:s',time()+config('strator.token_expires'));
        $authToken->save();

        Auth::onceUsingId($authToken->strator_id);

        return $next($request);
    }


}
